package main;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.logging.Logger;

import utils.SystemParm;

public class FileByYearAndQuarter {

	@SuppressWarnings("unused")
	private Logger logger = Logger.getLogger("picMove");
	@SuppressWarnings("unused")
	private Connection conn;

	/**
	 * 创建数据库连接
	 * 
	 * @throws IOException
	 */
	public FileByYearAndQuarter(String filePath) throws IOException {

		SystemParm.load(filePath);

		String url = SystemParm.getParm("db_url");
		String user = SystemParm.getParm("db_user");
		String password = SystemParm.getParm("db_password");
		try {
			Class.forName("com.mysql.jdbc.Driver");
			conn = DriverManager.getConnection(url, user, password);
			System.out.println("连接成功！");
		} catch (ClassNotFoundException e) {
			System.out.println("MySQL JDBC 驱动未找到！");
			e.printStackTrace();
		} catch (SQLException e) {
			System.out.println("数据库连接失败！");
			e.printStackTrace();
		} catch (Exception e) {
			e.getMessage();
		}
	}

	/**
	 * 复制图片（根据年份和季度）
	 * 
	 * @throws SQLException
	 */
	public void copyImg() throws IOException, SQLException {

		Integer yearId = SystemParm.getYearId();
		if (yearId == null) {
			logger.warning("年份信息：" + yearId + "为空,请输入年份信息后再提取");
		}
		List<Integer> quarters = SystemParm.getQuarterIds();
		if (quarters.size() == 0 || quarters == null) {
			logger.warning("季度信息：" + yearId + "为空,请输入季度信息后再提取");
		}
		List<Integer> brandIds = SystemParm.getBrandIds();

		for (int j = 0; j < quarters.size(); j++) {
			if (brandIds.size() == 0) {
				selectBarcode(yearId, quarters.get(j), 0);
			} else {
				for (int k = 0; k < brandIds.size(); k++) {
					selectBarcode(yearId, quarters.get(j), brandIds.get(k));
				}
			}

		}
	}

	/**
	 * 根据条码查找图片路径记录是否存在
	 * 
	 * @param barcode
	 * @return
	 * @throws SQLException
	 * @throws IOException
	 */
	public void selectBarcode(int year, int quarter, int brand) throws SQLException, IOException {

		String picInfo = "SELECT d.barcode FROM product a,`year` b,`quarter` c,product_barcode d WHERE a.year_ID = b.year_ID AND a.quarter_ID = c.quarter_ID AND a.product_ID = d.product_id AND a.year_ID = ?  AND a.quarter_ID = ?  ";
		if (brand != 0) {
			picInfo += " AND brand_ID = ?";
		}
		PreparedStatement params = conn.prepareStatement(picInfo);

		params.setInt(1, year);
		params.setInt(2, quarter);
		if (brand != 0) {
			params.setInt(3, brand);
		}
		ResultSet results = params.executeQuery();
		while (results.next()) {
			String barcode = results.getString("barcode");
			String sourcePath = SystemParm.getBackupPicPath() + "\\" + barcode + ".jpg";
			File sourceFile = new File(sourcePath);
			if (sourceFile.exists()) {
				File descFile = new File(SystemParm.getExtract() + "\\" + barcode + ".jpg");
				if (descFile.exists()) {					
					descFile.delete();
					logger.info("-----------已存在图片：2次复制：" + barcode);
					Files.copy(sourceFile.toPath(), descFile.toPath());
				} else {
					logger.info("-----------初次复制成功：" + barcode);
					Files.copy(sourceFile.toPath(), descFile.toPath());
				}
			} else {
				logger.warning(
						"-------- 年份：" + year + "---季度：" + quarter + " 品牌：" + brand + " 条码：" + barcode + "----不存在图片文件");
			}
		}
	}

	/**
	 * 入口
	 * 
	 * @param args
	 * @throws IOException
	 * @throws SQLException
	 */
	public static void main(String[] args) throws IOException, SQLException {
		FileByYearAndQuarter extractFile = new FileByYearAndQuarter(args[0]);
		File file = new File(SystemParm.getExtract());
		if (!file.exists()) {
			file.mkdirs();
		}
		extractFile.copyImg();

	}

}
